#include "StdAfx.h"
#include "WebConn.h"

CStringA T2UTF8(const CString& csStr)
{
	CStringW csUnicodeStr;
	CStringA csUtf8Str;
	DWORD dwBufLen;
	LPSTR lpszBuf;

	USES_CONVERSION;

	csUnicodeStr = CT2W(csStr);

	dwBufLen = csUnicodeStr.GetLength()*3+1;
	lpszBuf = csUtf8Str.GetBufferSetLength(dwBufLen);
	WideCharToMultiByte(CP_UTF8, 0, csUnicodeStr, -1, lpszBuf, dwBufLen, NULL, NULL);
	csUtf8Str.ReleaseBuffer();

	return csUtf8Str;
}

CString UTF82T(const CStringA& csStr)
{
	CStringW csUnicodeStr;
	DWORD dwBufLen;
	LPWSTR lpszBuf;
	CString csRet;

	USES_CONVERSION;

	dwBufLen = csStr.GetLength()+1;
	lpszBuf = csUnicodeStr.GetBufferSetLength(dwBufLen);
	MultiByteToWideChar(CP_UTF8, 0, csStr, -1, lpszBuf, dwBufLen);
	csUnicodeStr.ReleaseBuffer();

	csRet = CW2T((LPCWSTR)csUnicodeStr);
	return csRet;
}

CStringA T2UTF8(LPCTSTR lpszStr)
{
	return T2UTF8(CString(lpszStr));
}

CString UTF82T(LPCSTR lpszStr)
{
	return UTF82T(CStringA(lpszStr));
}

CString UrlEncode(LPCTSTR lpszStr)
{
	CString csRet;
	DWORD dwEncodeLen;
	LPTSTR lpBuf = NULL;

	dwEncodeLen = _tcslen(lpszStr)*4*3;
	lpBuf = csRet.GetBufferSetLength(dwEncodeLen);
	AtlEscapeUrl(lpszStr, lpBuf, NULL, dwEncodeLen, ATL_URL_ENCODE_PERCENT);
	csRet.ReleaseBuffer();

	csRet.Replace(_T("%3d"), _T("="));
	csRet.Replace(_T("%26"), _T("&"));
	return csRet;
}

CString UrlDecode(LPCTSTR lpszStr)
{
	CString csRet;
	DWORD dwInputLen;
	LPTSTR lpBuf = NULL;
	LPSTR lpUtf8Buf;
	DWORD dwUtf8Len;

	USES_CONVERSION;

	dwInputLen = _tcslen(lpszStr);
	lpUtf8Buf = new CHAR[dwInputLen+1];
	AtlUnescapeUrl(T2A(lpszStr), lpUtf8Buf, &dwUtf8Len, dwInputLen+1);
	csRet = UTF82T(lpUtf8Buf);
	delete[] lpUtf8Buf;

	return csRet;
}
